package com.famnote.randomchat;

import com.famnote.randomchat.R;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferNegotiator;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParserFactory;
 
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
 
public class MainActivity extends Activity {
	
	// Debugging
    private static final String TAG = "MainActivity";
    private static final boolean D = true;
    
    
    private static final int LOGIN_ACTIVITY = 0;
    
    
    
    // All static variables
    static final String URL = "http://push.appaas.com/hulbox/xml_rooms.php";
    // XML node keys
    static final String KEY_PROFILE = "profile"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_SUBTITLE = "subtitle";
    static final String KEY_LIKES = "likes";
    static final String KEY_THUMB_URL = "thumb_url";
    static final String KEY_OWNER = "owner";
 
    private Activity activity;
    
    ListView list;
    LazyAdapter adapter;
    
    ArrayList<HashMap<String, String>> profiles = null;
    
    private ProgressDialog dialog;
    
    private String mUserName;
    
    private String mProfileid;
    private String mTitle;
    private String mSubtitle;
    
    private String mNickname;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_main);
 
      //Remove title bar
        //////this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  
        //ActionBar actionBar = getActionBar();
        //ActionBar actionBar = getActionBar();
        //actionBar.show();
        
        
        activity = this;
        
        
        Bundle b = getIntent().getExtras();
		mNickname = b.getString("nickname");


		
        
        /*
        ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
         
        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element
 
        NodeList nl = doc.getElementsByTagName(KEY_SONG);
        // looping through all song nodes &lt;song&gt;
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key =&gt; value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
 
            // adding HashList to ArrayList
            songsList.add(map);
        }
        */
        
               
        list=(ListView)findViewById(R.id.list);
 
        // Getting adapter by passing xml data ArrayList
        //adapter=new LazyAdapter(this, songsList);
        //list.setAdapter(adapter);
 
        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 
            	String profileid = profiles.get(position).get("id");
            	
            	if (profileid.equals("")) {
            		
                	Intent i = new Intent(activity, Chat.class);
                	
                	String title = profiles.get(position).get("title");
                	i.putExtra("title", title);
                	String subtitle = profiles.get(position).get("subtitle");
                	i.putExtra("subtitle", subtitle);
                	

                	
                	startActivity(i);
                	
            	} else {

                	Intent i = new Intent(activity, GroupChat.class);
                	
                	i.putExtra("nickname", mNickname);
                	
                	
                	i.putExtra("roomid", profileid);
                	
                	String title = profiles.get(position).get("title");
                	i.putExtra("title", title);
                	String subtitle = profiles.get(position).get("subtitle");
                	i.putExtra("subtitle", subtitle);
                	String bgurl = profiles.get(position).get("bg_url");
                	i.putExtra("bgurl", bgurl);
                	
                	startActivity(i);
            		
                	
            		
            		
                	/*
                	mProfileid = profileid;
            		
                	mTitle = profiles.get(position).get("title");
                	
                	mSubtitle = profiles.get(position).get("subtitle");
                	
                	
                	String msg = getResources().getString(R.string.loading);
                    dialog = ProgressDialog.show(activity, "", msg, true);
                    
            		// Creating a new non-ui thread task to download xml data 
                    NickNameTask nicknameTask = new NickNameTask();
                    // Starting the download process
                    nicknameTask.execute("http://push.appaas.com/hulbox/of_nickname.php?roomid=" + mProfileid);
					*/
            		
            	}
            	
            	
            }
            
        });
        
        
        
        String msg = getResources().getString(R.string.loading);	
        dialog = ProgressDialog.show(this, "", msg, true);

        // Creating a new non-ui thread task to download xml data 
        DownloadTask downloadTask = new DownloadTask();

        // Starting the download process
        downloadTask.execute(URL);
    }

    
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

    }
    
    /*
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_BACK) { 
            
        	dialog.dismiss();
        	finish();
            
        	
            return true; 
        } 
        return super.onKeyDown(keyCode, event);
    }
    */
    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        
        inflater.inflate(R.menu.activity_main, menu);
        
        return true;
    }


    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	
        switch (item.getItemId()) {
        

        case R.id.menu_refresh:
        	
            String msg = getResources().getString(R.string.loading);	
            dialog = ProgressDialog.show(this, "", msg, true);

            // Creating a new non-ui thread task to download xml data 
            DownloadTask downloadTask = new DownloadTask();

            // Starting the download process
            downloadTask.execute(URL);
        	
        	return true;
        	
        /*
        case R.id.menu_findroom:
        	
        	Intent i = new Intent();
        	
        	i.setClassName("com.famnote.randomchat", "com.famnote.randomchat.LoginActivity");
        	startActivity(i);
        	
        	
        	return true;
        */
        	
        case R.id.menu_createroom:
        	/*
        	Intent i = new Intent();
        	
        	i.setClassName("com.famnote.randomchat", "com.famnote.randomchat.LoginActivity");
        	startActivity(i);
        	*/
        	
        	//Intent i = new Intent(this, LoginActivity.class);
        	//startActivityForResult(i, LOGIN_ACTIVITY);

        	
        	/*
        	Intent i = new Intent(this, GroupChat.class);
        	
    		//String room = mProfileid + "@conference.push.appaas.com";
    		//i.putExtra("room", room);
    		
    		i.putExtra("title", mTitle);
    		
    		i.putExtra("subtitle", mSubtitle);
    		
    		String nickName = "hithere";
    		
    		i.putExtra("nickname", nickName);
     
    		startActivity(i);
        	*/
        	Intent i = new Intent(this, CreateRoomActivity.class);
        	i.putExtra("nickname", mNickname);
        	startActivity(i);
        	
        	return true;
        	
       /* 	
        case R.id.menu_settings:
        	
        	i = new Intent(this, WebViewActivity.class);
        	startActivity(i);
        	
        	return true;
        */
        	/*
        case R.id.username:
        	
            // Launch the UserNameActivity to see devices and do scan
            Intent userNameIntent = new Intent(this, UserNameActivity.class);
            startActivityForResult(userNameIntent, INTENT_GET_USERNAME); 
            
        	
        	
        	Intent takePic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(takePic, LOAD_IMAGE_GALLERY);
            
        	

            
            
            return true;

        	*/
        	
        }
		
        
        return false;
    }
    
    
    
    
    /** A method to download xml data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);
                
                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();
                
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                
                StringBuffer sb  = new StringBuffer();
                
                String line = "";
                while( ( line = br.readLine())  != null){
                	sb.append(line);
                }
                
                
                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
                if(D) Log.e(TAG, e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }
    
    /** AsyncTask to download xml data */
    private class DownloadTask extends AsyncTask<String, Integer, String>{
        String data = null;
                
        @Override
        protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);
                            
                            //if(D) Log.e(TAG, data);
                            
                        }catch(Exception e){
                        	Log.d("Background Task",e.toString());
                        }
                        return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
                        // The parsing of the xml data is done in a non-ui thread 
                        //ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
                        
                        // Start parsing xml data
                        //listViewLoaderTask.execute(result);
                        
                	StringReader reader = null;
                	
                	try{
        				reader = new StringReader(result);
        	        }catch(Exception e){
        	        	Log.d("XML Exception1",e.toString());
        	        }
        	        
        			
        			// Instantiating xml parser class
        			ProfileXmlParser profileXmlParser = new ProfileXmlParser();
        		
        			// A list object to store the parsed countries list
        	        //ArrayList<HashMap<String, String>> profiles = null;
        	        
        	        try{
        	        	// Getting the parsed data as a List construct
        	        	profiles = profileXmlParser.parse(reader);
        	        }catch(Exception e){
        	        	Log.d("Exception",e.toString());
        	        }
        	               

        	        /*
        	        // Keys used in Hashmap 
        	        String[] from = { "country","flag","details"};

        	        // Ids of views in listview_layout
        	        int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};
                	*/
                	
        	     // Getting adapter by passing xml data ArrayList
        	        adapter=new LazyAdapter(activity, profiles);
        	        list.setAdapter(adapter);
        	     // Noticing listview about the dataset changes
        			adapter.notifyDataSetChanged();	
                	
        			
        			dialog.dismiss();
        			dialog = null;
          }
    }
    
    
    
    
    
    /** AsyncTask to download xml data */
    private class NickNameTask extends AsyncTask<String, Integer, String>{
        String data = null;
                @Override
                protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);
                                
                        }catch(Exception e){
                        	Log.d("Background Task",e.toString());
                        }
                        return data;
                }

                @Override
                protected void onPostExecute(String result) {
                	
                	dialog.dismiss();
                	
                	
                	Intent i = new Intent();
                	
            		i.setClassName("com.famnote.randomchat", "com.famnote.randomchat.GroupChat");

            		
            		//i.setClassName("com.famnote.randomchat", "com.famnote.randomchat.Chat");
            		//i.setClassName("com.famnote.randomchat", "com.famnote.randomchat.WebViewActivity");
            		//i.setClassName("com.famnote.randomchat", "com.famnote.randomchat.MainActivity");
	            
            		String room = mProfileid + "@conference.push.appaas.com";
            		i.putExtra("room", room);
            		
            		i.putExtra("title", mTitle);
            		
            		i.putExtra("subtitle", mSubtitle);
            		
            		String nickName;
            		if (result == null) {
            			nickName = getResources().getString(R.string.anonymous);
            		} else {
            			nickName = result;
            		}
            		
            		i.putExtra("nickname", nickName);
	         
            		startActivity(i);
            		
            		
                	
                }
    }
    
    
    
    
}

